let root = document.documentElement;

function getCurrentDuration() {
  // string split
  var arr = getComputedStyle(document.documentElement).getPropertyValue('--earth-orbit-duration').split("s");
  // string to integer
  var duration = Number(arr[0])
  return duration
}

function postDuration(duration) {
  var Params = {"orbit_duration": duration};
  $.ajax({
      type: "POST",
      url: "/api/v1/orbit_duration",
      data: Params,
      dataType: "json",
      error:function(Message){
      },
      success: function(Message) {
        //var content = JSON.stringify(Message)
        //alert(content)
      }        
  });
}

function postDummyData(dummy_data) {
  var Params = {"dummy": dummy_data};
  $.ajax({
      type: "POST",
      url: "/api/v1/dummy",
      data: Params,
      dataType: "json",
      error:function(Message){
      },
      success: function(Message) {
        //var content = JSON.stringify(Message)
        //alert(content)
      }        
  });
}

//function incEarthOrbitSpeed() {
//  var duration = getCurrentDuration()
//  duration -= 1.0
//  if(duration < 0.0){
//    duration = 12.00021
//  }
//  //alert(duration)
//  root.style.setProperty('--earth-orbit-duration', duration + "s");
//  //postDuration(duration)
//}

//function decEarthOrbitSpeed() {
//  var duration = getCurrentDuration()
//  duration += 1.0
//  if(duration > 12.00021){
//    duration = 12.00021
//  }
//  //alert(duration)
//  root.style.setProperty('--earth-orbit-duration', duration + "s");
//  //postDuration(duration)
//}

//function setEarthOrbitSpeed() {
//  root.style.setProperty('--earth-orbit-duration', 12.00021 + "s");
//  //postDuration(12.00021)
//}


var postInterval = 1000;
var DummyData = "";
//定时器数组
var timer = new Array(100);
var timer_idx = 0;

function incEarthOrbitSpeed() {
  //前端Web图形化显示
  var duration = getCurrentDuration()
  duration -= 1.0
  if(duration < 0.0){
    duration = 12.00021
  }
  //alert(duration)
  root.style.setProperty('--earth-orbit-duration', duration + "s");

  // 构造dummy data
  for (var idx=0; idx<1024; idx++) {
    DummyData+="req."
  }
  //alert(DummyData)
  //定时post 任务到后端服务
  postInterval -= 50
  if(postInterval < 0) {
    postInterval = 1000
  }
  timer[timer_idx++] = setInterval(function postWorkload() {
      var Params = {"dummy": DummyData};
      $.ajax({
          type: "POST",
          url: "/api/v1/dummy",
          data: Params,
          dataType: "json",
          error:function(Message){
          },
          success: function(Message) {
          }        
      });
    }, postInterval);
}

function setEarthOrbitSpeed() {
  root.style.setProperty('--earth-orbit-duration', 12.00021 + "s");

  postInterval = 1000
  // 清除所有的定时任务
  for(var i = 0; i < timer_idx; i++){
    clearInterval(timer[i])
  }
}
